package com.yilin.parents.wxapi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.MainActivity;
import com.molyfun.parents.activity.account.CompletedInformationActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.common.ShareDialogActivity;
import com.molyfun.parents.push.PushMsgCacheCenter;
import com.molyfun.parents.rest.bean.RegThirdPartyResponse;
import com.molyfun.parents.rest.bean.ThirdBeanResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.SecurityUtil;
import com.molyfun.parents.utils.StringUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:3/8/17.
 */

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
    private static final String WX_APPSECRET = "69dd72991569be39598ddbb39ca95773";
    private static final int RETURN_MSG_TYPE_LOGIN = 1; //登录
    private static final int RETURN_MSG_TYPE_SHARE = 2; //分享
    private IWXAPI api;
    private String code;
    private String nonce;

    private static int mCurrentWxBindType = WXBindType.TypeLogin;

    private interface WXBindType{
        int TypeLogin = 1001;
        int TypeBind = 1002;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       /* api = WXAPIFactory.createWXAPI(this, ShareDialogActivity.APP_ID, false);

        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

//        MFPApplication.sApi.handleIntent(getIntent(), this);
        api = WXAPIFactory.createWXAPI(this, ShareDialogActivity.WX_APP_ID);
//        api.registerApp(ShareDialogActivity.WX_APP_ID);
        api.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {



    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

//        Toast.makeText(this, "baseresp.getType = " + resp.getType(), Toast.LENGTH_SHORT).show();
        int type = resp.getType(); //类型：分享还是登录
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if(type == RETURN_MSG_TYPE_LOGIN) {
                    result = R.string.errcode_login_success;
                    // 获取code
                    code = ((SendAuth.Resp) resp).code;
                    System.out.println("WXEntryActivity" + code);
                    wxLogin(code);
                }else if(type == RETURN_MSG_TYPE_SHARE){
                    result = R.string.errcode_share_success;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if(type == RETURN_MSG_TYPE_LOGIN) {
                    result = R.string.errcode_login_cancel;
                }else if(type == RETURN_MSG_TYPE_SHARE) {
                    result = R.string.errcode_share_cancel;
                }
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                if(type == RETURN_MSG_TYPE_LOGIN) {
                    result = R.string.errcode_login_deny;
                }else if(type == RETURN_MSG_TYPE_SHARE) {
                    result = R.string.errcode_share_deny;
                }
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                if(type == RETURN_MSG_TYPE_LOGIN) {
                    result = R.string.errcode_login_unsupported;
                }else if(type == RETURN_MSG_TYPE_SHARE) {
                    result = R.string.errcode_share_unsupported;
                }
                break;
            default:
                if(type == RETURN_MSG_TYPE_LOGIN) {
                    result = R.string.errcode_login_unknown;
                }else if(type == RETURN_MSG_TYPE_SHARE) {
                    result = R.string.errcode_share_unknown;
                }
                break;
        }
        toast(result);
        finish();
    }

    /**
     * 微信组件注册初始化
     *
     * @param context       上下文
     * @param weixin_app_id appid
     * @return 微信组件api对象
     */

    public static IWXAPI initWeiXin(Context context, String weixin_app_id) {
        if (TextUtils.isEmpty(weixin_app_id)) {
            Toast.makeText(context.getApplicationContext(), "app_id 不能为空", Toast.LENGTH_SHORT).show();
        }
        IWXAPI api = WXAPIFactory.createWXAPI(context, weixin_app_id, true);
        api.registerApp(weixin_app_id);
        return api;
    }

    /**
     * 登录微信
     *
     * @param api 微信服务api
     */
    public static void loginWeixin(Context context, IWXAPI api) {
        mCurrentWxBindType = WXBindType.TypeLogin;
        // 判断是否安装了微信客户端
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context.getApplicationContext(), "您还未安装微信客户端！", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送授权登录信息，来获取code
        SendAuth.Req req = new SendAuth.Req();
        // 应用的作用域，获取个人信息
        req.scope = "snsapi_userinfo";
        /**
         * 用于保持请求和回调的状态，授权请求后原样带回给第三方
         * 为了防止csrf攻击（跨站请求伪造攻击），后期改为随机数加session来校验
         */
        req.state = "app_wechat";
        api.sendReq(req);
    }

    /**
     * 登录微信
     *
     * @param api 微信服务api
     */
    public static void bindWeixin(Context context, IWXAPI api) {
        mCurrentWxBindType = WXBindType.TypeBind;
        // 判断是否安装了微信客户端
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context.getApplicationContext(), "您还未安装微信客户端！", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送授权登录信息，来获取code
        SendAuth.Req req = new SendAuth.Req();
        // 应用的作用域，获取个人信息
        req.scope = "snsapi_userinfo";
        /**
         * 用于保持请求和回调的状态，授权请求后原样带回给第三方
         * 为了防止csrf攻击（跨站请求伪造攻击），后期改为随机数加session来校验
         */
        req.state = "app_wechat";
        api.sendReq(req);
    }


    private void wxLogin(final String code) {
        final long timesptamp = System.currentTimeMillis();
        final String nonce = StringUtils.alphabetTo10Random();
        Map<String, String> map = new HashMap<>();
        map.put("nonce", nonce);
        map.put("timestamp", String.valueOf(timesptamp));
        map.put("signature", nonce + String.valueOf(timesptamp) + "MOLYFUN-GAMECOLLECTION");

        final String signature = SecurityUtil.checkSignature(map);

        if(mCurrentWxBindType == WXBindType.TypeLogin){
            Call<RegThirdPartyResponse> call = MFPApplication.getInstance().getRestClient().wxlogin(code, nonce, String.valueOf(timesptamp), signature, "mobile");
            call.enqueue(new Callback<RegThirdPartyResponse>() {
                @Override
                public void onResponse(Call<RegThirdPartyResponse> call, Response<RegThirdPartyResponse> response) {
                    System.out.println("----->wx");
                    if (response.body() != null && response.body().getMsg() != null) {
                        if (response.body().getCode() == 200) {
                            System.out.println("----->wx200");
                            if(response.body().getData() != null) {
                                PreferencesStorageUtil.setToken(WXEntryActivity.this, response.body().getData().getToken());
                                PreferencesStorageUtil.setUserBean(WXEntryActivity.this, GsonUtil.toJson(response.body().getData()));
                                PreferencesStorageUtil.setIMUserName(WXEntryActivity.this, response.body().getData().getImusername());
                                PreferencesStorageUtil.setIMUserPwd(WXEntryActivity.this, response.body().getData().getImpassword());
                                PreferencesStorageUtil.setPhoneNum(WXEntryActivity.this, response.body().getData().getPhone());
                                PreferencesStorageUtil.setAddress(WXEntryActivity.this, response.body().getData().getAddress());
                                PreferencesStorageUtil.setEmail(WXEntryActivity.this, response.body().getData().getEmail());
                                PreferencesStorageUtil.setStudentId(WXEntryActivity.this, response.body().getData().getStudentid());
                                PreferencesStorageUtil.setThirdBindingStatu(WXEntryActivity.this, response.body().getData().getThirdlist().get(0).getStatus());
                                PreferencesStorageUtil.setThirdAccount(WXEntryActivity.this, response.body().getData().getThirdlist().get(0).getUsername());
                                PreferencesStorageUtil.setThirdOpenId(WXEntryActivity.this, response.body().getData().getThirdlist().get(0).getOpenid());
                                if (TextUtils.isEmpty(response.body().getData().getStudentid())) {
                                    PreferencesStorageUtil.setUserEnter(WXEntryActivity.this, false);
                                } else {
                                    PreferencesStorageUtil.setUserEnter(WXEntryActivity.this, true);
                                    PreferencesStorageUtil.setOriganOutShowSplash(MFPApplication.getInstance(), false);
                                }
                                MFPApplication.getInstance().refreshRestClient(response.body().getData().getToken());
                                PushMsgCacheCenter.getInstance().setmCurrentUnreadCount(response.body().getData().getMessageunreadcount());

                                Intent toMainIntent = new Intent(WXEntryActivity.this, MainActivity.class);
                                WXEntryActivity.this.startActivity(toMainIntent);
                                finish();
                            }
                        } else if (response.body().getCode() == 1020) {
//                            System.out.println("----->wx1020");
                            System.out.println("code" + code + "alphabetTo10Random" + nonce + "curretime" + timesptamp + "signature" + signature+"openid"+response.body().getMsg());
//                        startActivity(new Intent(WXEntryActivity.this, CompletedInformationActivity.class));
                            CompletedInformationActivity.startyActivity(WXEntryActivity.this,nonce,String.valueOf(timesptamp),signature,response.body().getMsg());
                        }else {
                            toast(response.body() == null ?"" :response.body().getMsg());
                        }
                    }
                }

                @Override
                public void onFailure(Call<RegThirdPartyResponse> call, Throwable t) {

                }
            });
        }else{

            Call<ThirdBeanResponse> call = MFPApplication.getInstance().getRestClient().bindThirdParty(code);
            call.enqueue(new Callback<ThirdBeanResponse>() {
                @Override
                public void onResponse(Call<ThirdBeanResponse> call, Response<ThirdBeanResponse> response) {
//                    System.out.println("----->wx");
                    if (response.body() != null && response.body().getMsg() != null) {
                        if (response.body().getCode() == 200) {

                            PreferencesStorageUtil.setThirdBindingStatu(WXEntryActivity.this, response.body().getData().getStatus());
                            PreferencesStorageUtil.setThirdAccount(WXEntryActivity.this, response.body().getData().getUsername());
                            PreferencesStorageUtil.setThirdOpenId(WXEntryActivity.this, response.body().getData().getOpenid());

                            Message uimessage = new Message();
                            uimessage.what = EventDispatcherEnum.UI_EVENT_BIND_WX;
                            MFPApplication.getInstance().getEventDispatcher().sendMessage(uimessage);

                        }
                    }

                }

                @Override
                public void onFailure(Call<ThirdBeanResponse> call, Throwable t) {

                }
            });

        }
    }
}
